package com.huayi.server.NioServer;

import com.alibaba.fastjson.JSON;


import com.huayi.server.Entity.DeviceEntity;
import io.netty.util.concurrent.FailedFuture;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

@Component
public class DeviceManager {

    @Autowired
    JedisPool jedisPool;

    private String id;  //根节点ID
    private int type;   //操作类型

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    Logger logger = LoggerFactory.getLogger(DeviceManager.class);

    ConcurrentHashMap<String,ServerHandler> deviceHandlerMap = new ConcurrentHashMap<String, ServerHandler>();


    Jedis jedis;

    String DEVICE_HSET_KEY = "device_hset_key";

    byte[] DEVICE_HSET_KEY_DATA = DEVICE_HSET_KEY.getBytes(Charset.defaultCharset());

    public void list(){
        Jedis jedis;
        jedis = jedisPool.getResource();
        Map<byte[], byte[]> map = jedis.hgetAll(DEVICE_HSET_KEY_DATA);
        jedis.close();
//        logger.info("map:"+map.toString());
//        for (byte[] name : map.keySet()){
//            logger.info("name:" + new String(name));
//        }
        for (byte[] data : map.values()){
            DeviceEntity device = JSON.parseObject(data,DeviceEntity.class);
            logger.debug("value:"+device.toString());
        }
    }

    public void add(DeviceEntity device){
        Jedis jedis;
        jedis = jedisPool.getResource();
        byte[] data = JSON.toJSONBytes(device);
        jedis.hset(DEVICE_HSET_KEY_DATA, device.getDeviceId().getBytes(),data);
        jedis.close();
    }

    public DeviceEntity get(String id){
        Jedis jedis;
        jedis = jedisPool.getResource();
        byte[] data = jedis.hget(DEVICE_HSET_KEY_DATA,id.getBytes());
        if (data==null){
            return null;
        }
        DeviceEntity device = JSON.parseObject(data,DeviceEntity.class);
        jedis.close();
        return device;
    }

    public List<DeviceEntity> allInfo(){
        Jedis jedis = jedisPool.getResource();
        Map<byte[],byte[]> map = jedis.hgetAll(DEVICE_HSET_KEY_DATA);
        if (map==null){
            return null;
        }
        List<DeviceEntity> list = new ArrayList<DeviceEntity>();
        for (byte[] data : map.values()){
            DeviceEntity device = JSON.parseObject(data,DeviceEntity.class);
            list.add(device);
        }
        jedis.close();
        return list;
    }

//    public Boolean ctl(Device device){
//        ServerHandler handler = deviceHandlerMap.get(id);
//        Message message = new Message();
//        List<Device> list = new ArrayList<Device>();
//        list.add(device);
//        message.setData(list);
//        return sendMessage(handler,message);
//    }


    public Future multiCtl(List<DeviceEntity> deviceList){
        ServerHandler handler = deviceHandlerMap.get(id);
        if (handler == null){
            return new FailedFuture(GlobalEventExecutor.INSTANCE,new Throwable("handler is null..."));
        }
        Message message = new Message();
        message.setDevicelist(deviceList);
        message.setLen(6+10*deviceList.size());//这个不需要在这里计算
        message.setKey(0);
        message.setApi(0);
        message.setApi(type);
        message.setData_len(deviceList.size());
        return handler.sendMessage(message);
    }

    private Boolean sendMessage(ServerHandler handler,Message message){
        Future<Boolean> sendMessageFuture = handler.sendMessage(message);
//        try {
//            if (sendMessageFuture.await(5, TimeUnit.SECONDS) && sendMessageFuture.isSuccess()){
//                return true;
//            }
//        } catch (InterruptedException e) {
//            logger.debug("sendMessage error...");
//            e.printStackTrace();
//        }
        return false;
    }

    public void addHandler(String id,ServerHandler handler){
        logger.debug("id:"+id+",handler:"+handler.toString());
        deviceHandlerMap.put(id,handler);
    }


}
